import Koa from 'koa';
import Router from 'koa-router';
import bodyParser from 'koa-bodyparser';
import Consul from 'consul';

interface ServiceConfig {
    name: string;
    id: string;
    address: string;
    port: number;
    healthCheckPath: string;
    checkInterval: string;
    checkTimeout: string;
}

const config: ServiceConfig = {
    name: 'your-service',
    id: process.env.SERVICE_ID ?? 'your-service-1',
    address: '95.169.25.181',
    port: Number(process.env.PORT) || 3000,
    healthCheckPath: '/health',
    checkInterval: '10s',
    checkTimeout: '5s',
};

async function main() {
    const app = new Koa();
    const router = new Router();

    router.get('/', async (ctx) => {
        ctx.body = `Consul serviceName is ${config.name}, serviceId ${config.id}`;
    });

    // 健康检查路由
    router.get(config.healthCheckPath, async (ctx) => {
        ctx.status = 200; // 200 表示服务正常
        ctx.body = 'OK';
    });

    app.use(bodyParser());
    app.use(router.routes());

    // 创建 Consul 客户端
    const consul = new Consul({
        host: config.address,
        port: '8500',
    });

    // 注册服务
    const serviceDetails = {
        name: config.name,
        id: config.id,
        address: config.address,
        port: config.port,
        check: {
            http: `http://${config.address}:${config.port}${config.healthCheckPath}`,
            interval: config.checkInterval,
            timeout: config.checkTimeout,
        },
    };

    try {
        await consul.agent.service.register(serviceDetails);
        console.log(`Service registered successfully: ${config.name} (${config.id})`);
    } catch (error) {
        console.error('Failed to register service:', error);
        process.exit(1);
    }

    // 启动 Koa 服务器
    app.listen(config.port, () => {
        console.log(`Server is running on http://localhost:${config.port}`);
    });
}

main();
